package cn.gmy.progect1;

import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelParser {
	private static final Log logger = LogFactory.getLog(ExcelParser.class);

	public static String[] parseExcelData(InputStream inputStream, String fileName) {
		List<String> resultList = new ArrayList<>();
		Workbook workbook = null;
		try {
			if (fileName.endsWith("xls")) {
				workbook = new HSSFWorkbook(inputStream);
			} else if (fileName.endsWith("xlsx")) {
				workbook = new XSSFWorkbook(inputStream);
			} else {
				throw new RuntimeException("您选择的文件不是一个Excel文件...");
			}

			Sheet hSheet = workbook.getSheetAt(0);
			Iterator<Row> rowIterator = hSheet.iterator();
			while (rowIterator.hasNext()) {
				Row row = rowIterator.next();
				Iterator<Cell> cellIterator = row.cellIterator();
				String result = "";
				while (cellIterator.hasNext()) {
					Cell cell = cellIterator.next();

					switch (cell.getCellTypeEnum()) {
					case BLANK:
						result += "";
						break;
					case NUMERIC:
						// 解析整数与小数的问题
						if (!DateUtil.isCellDateFormatted(cell)) {
							long ii = Math.round(cell.getNumericCellValue());
							if (Double.parseDouble(ii + ".0") == cell.getNumericCellValue()) {
								result += String.valueOf(ii) + "\t";
							} else {
								result += String.valueOf(cell.getNumericCellValue()) + "\t";
							}
						} else {
							// 解析日期时间类型
							Date date = cell.getDateCellValue();
							DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
							result += df.format(date) + "\t";
						}
						break;
					case FORMULA:
						result += String.valueOf(cell.getCellFormula()) + "\t";
						break;
					case STRING:
						result += cell.getStringCellValue() + "\t";
						break;
					default:
						break;
					}
				}
				resultList.add(result.toString());
			}
		} catch (IOException e) {
			logger.error("IO Exception : File not found " + e);
		}

		return resultList.toArray(new String[0]);
	}

}
